package com.employeemanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.employeemanage.domain.bean.TblEmployee;
import com.employeemanage.domain.bean.TblEmployeeSchedule;
import com.employeemanage.domain.resp.PageResult;
import com.employeemanage.domain.vo.BatchScheduleResponseVo;
import com.employeemanage.domain.vo.BatchScheduleVo;
import com.employeemanage.domain.vo.EmployeeScheduleListVo;
import com.employeemanage.domain.vo.EmployeeScheduleResponseVo;
import com.employeemanage.mapper.TblEmployeeMapper;
import com.employeemanage.mapper.TblEmployeeScheduleMapper;
import com.employeemanage.service.TblEmployeeScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 郭可欣
* @description 针对表【tbl_employee_schedule(员工排班表)】的数据库操作Service实现
* @createDate 2025-07-05 14:17:39
*/
@Service
public class TblEmployeeScheduleServiceImpl extends ServiceImpl<TblEmployeeScheduleMapper, TblEmployeeSchedule>
    implements TblEmployeeScheduleService{

    @Autowired
    private TblEmployeeMapper employeeMapper;

    @Override
    public PageResult<EmployeeScheduleResponseVo> getEmployeeScheduleList(EmployeeScheduleListVo vo) {
        // 如果按员工姓名查询，先查询员工ID
        List<Long> employeeIds = null;
        if (StringUtils.hasText(vo.getEmployeeName())) {
            LambdaQueryWrapper<TblEmployee> employeeWrapper = new LambdaQueryWrapper<>();
            employeeWrapper.like(TblEmployee::getName, vo.getEmployeeName());
            List<TblEmployee> employees = employeeMapper.selectList(employeeWrapper);
            employeeIds = employees.stream().map(TblEmployee::getId).collect(Collectors.toList());
            
            // 如果没有找到匹配的员工，返回空结果
            if (employeeIds.isEmpty()) {
                return new PageResult<>(vo.getPageSize().longValue(), vo.getPageNum().longValue(), 
                    new ArrayList<>(), 0L);
            }
        }
        
        // 构建查询条件
        LambdaQueryWrapper<TblEmployeeSchedule> wrapper = new LambdaQueryWrapper<>();
        
        if (vo.getEmployeeId() != null) {
            wrapper.eq(TblEmployeeSchedule::getEmployeeId, vo.getEmployeeId());
        } else if (employeeIds != null) {
            wrapper.in(TblEmployeeSchedule::getEmployeeId, employeeIds);
        }
        
        if (StringUtils.hasText(vo.getStartDate())) {
            wrapper.ge(TblEmployeeSchedule::getScheduleDate, vo.getStartDate());
        }
        
        if (StringUtils.hasText(vo.getEndDate())) {
            wrapper.le(TblEmployeeSchedule::getScheduleDate, vo.getEndDate());
        }
        
        if (StringUtils.hasText(vo.getShiftType())) {
            wrapper.eq(TblEmployeeSchedule::getShiftType, vo.getShiftType());
        }
        
        wrapper.orderByDesc(TblEmployeeSchedule::getScheduleDate);
        
        // 分页查询
        Page<TblEmployeeSchedule> page = new Page<>(vo.getPageNum(), vo.getPageSize());
        Page<TblEmployeeSchedule> resultPage = this.page(page, wrapper);
        
        // 转换为响应VO
        List<EmployeeScheduleResponseVo> responseList = resultPage.getRecords().stream()
                .map(this::convertToResponseVo)
                .collect(Collectors.toList());
        
        return new PageResult<>(resultPage.getSize(), resultPage.getCurrent(), responseList, resultPage.getTotal());
    }

    @Override
    @Transactional
    public BatchScheduleResponseVo batchSchedule(BatchScheduleVo vo) {
        BatchScheduleResponseVo response = new BatchScheduleResponseVo();
        List<String> conflicts = new ArrayList<>();
        int successCount = 0;
        int conflictCount = 0;
        
        // 检查冲突
        for (Long employeeId : vo.getEmployeeIds()) {
            for (String date : vo.getDates()) {
                // 检查是否已有排班
                LambdaQueryWrapper<TblEmployeeSchedule> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TblEmployeeSchedule::getEmployeeId, employeeId)
                       .eq(TblEmployeeSchedule::getScheduleDate, date);
                
                TblEmployeeSchedule existing = this.getOne(wrapper);
                if (existing != null) {
                    // 获取员工姓名
                    TblEmployee employee = employeeMapper.selectById(employeeId);
                    String employeeName = employee != null ? employee.getName() : "未知员工";
                    conflicts.add("员工" + employeeName + "在" + date + "已有排班");
                    conflictCount++;
                }
            }
        }
        
        // 如果没有冲突，进行批量排班
        if (conflicts.isEmpty()) {
            List<TblEmployeeSchedule> schedules = new ArrayList<>();
            Date now = new Date();
            
            for (Long employeeId : vo.getEmployeeIds()) {
                for (String date : vo.getDates()) {
                    TblEmployeeSchedule schedule = new TblEmployeeSchedule();
                    schedule.setEmployeeId(employeeId);
                    schedule.setScheduleDate(parseDate(date));
                    schedule.setShiftType(vo.getShiftType());
                    schedule.setScheduledAt(now);
                    schedules.add(schedule);
                }
            }
            
            // 批量保存
            this.saveBatch(schedules);
            successCount = schedules.size();
        }
        
        response.setSuccessCount(successCount);
        response.setConflictCount(conflictCount);
        response.setConflicts(conflicts);
        
        return response;
    }

    @Override
    public boolean deleteSchedule(Long id) {
        return this.removeById(id);
    }
    
    /**
     * 转换为响应VO
     */
    private EmployeeScheduleResponseVo convertToResponseVo(TblEmployeeSchedule schedule) {
        EmployeeScheduleResponseVo vo = new EmployeeScheduleResponseVo();
        vo.setId(schedule.getId());
        vo.setEmployeeId(schedule.getEmployeeId());
        vo.setScheduleDate(formatDate(schedule.getScheduleDate()));
        vo.setShiftType(schedule.getShiftType());
        vo.setScheduledAt(formatDateTime(schedule.getScheduledAt()));
        
        // 获取员工姓名
        TblEmployee employee = employeeMapper.selectById(schedule.getEmployeeId());
        vo.setEmployeeName(employee != null ? employee.getName() : "未知员工");
        
        return vo;
    }
    
    /**
     * 格式化日期
     */
    private String formatDate(Date date) {
        if (date == null) return null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }
    
    /**
     * 格式化日期时间
     */
    private String formatDateTime(Date date) {
        if (date == null) return null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }
    
    /**
     * 解析日期字符串
     */
    private Date parseDate(String dateStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.parse(dateStr);
        } catch (Exception e) {
            throw new RuntimeException("日期格式错误: " + dateStr);
        }
    }
}




